package com.sr.srinterpolation.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.sr.srinterpolation.R;
import com.sr.srinterpolation.databinding.ActivityMainBinding;
import com.sr.srinterpolation.util.ImageUtil;
import com.sr.srinterpolation.util.LagrangeInterpolationUtil;
import com.sr.srinterpolation.util.LatexUtil;
import com.sr.srinterpolation.util.NewtonInterpolationUtil;

import org.scilab.forge.jlatexmath.core.AjLatexMath;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "MainActivity";

    private static final int TYPE_LAGRANGE = 0;
    private static final int TYPE_NEWTON = 1;

    private ActivityMainBinding binding;
    private int type;
    private String latexString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化公式显示控件
        AjLatexMath.init(this);

        // 初始化类型
        setType(TYPE_LAGRANGE);
        // 按钮点击事件
        binding.btnChooseType.setOnClickListener(v -> chooseTypeBtn());
        binding.btnLagrange0.setOnClickListener(v -> generateBtnClick(0));
        binding.btnLagrange1.setOnClickListener(v -> generateBtnClick(1));
        binding.btnLagrange2.setOnClickListener(v -> generateBtnClick(2));
        binding.btnSave.setOnClickListener(v -> saveBtnClick());
    }

    // 设置类型
    private void setType(int type) {
        this.type = type;
        String typeString = null;
        switch (type) {
            case TYPE_LAGRANGE:
                typeString = "拉格朗日插值法";
                break;

            case TYPE_NEWTON:
                typeString = "牛顿插值法";
                break;
        }
        binding.tvType.setText(typeString);
    }

    // 插值法类型选择按钮点击事件
    private void chooseTypeBtn() {
        String[] types = {"拉格朗日插值法", "牛顿插值法"};
        new AlertDialog.Builder(this)
                .setTitle("请选择插值法类型")
                .setItems(types, (dialogInterface, i) -> setType(i))
                .create()
                .show();
    }

    // 按钮点击事件
    private void generateBtnClick(int add) {
        String text = binding.etInput.getText().toString();
        if (TextUtils.isEmpty(text)) {
            showNotice("请输入数字");
            return;
        }
        if (!text.matches("[0-9 ,]+")) {
            showNotice("格式错误");
            return;
        }
        // 从输入框中取出数列
        String[] strs = text.split("[ ,]");
        int n = strs.length;
        if (n == 0 || n + add < 2) {
            showNotice("数列过短或格式错误");
            return;
        }
        int[] y = new int[n + add];
        try {
            for (int i = 0; i < n; i++) {
                String str = strs[i];
                if (TextUtils.isEmpty(str)) {
                    showNotice("格式错误");
                }
                y[i] = Integer.parseInt(str);
            }
        } catch (NumberFormatException e) {
            showNotice("格式错误");
        }
        // 添加项
        if (add >= 1) {
            y[n] = 114514;
        }
        if (add >= 2) {
            y[n + 1] = 1919810;
        }
        // 生成x数组
        int[] x = new int[y.length];
        for (int i = 0; i < x.length; i++) {
            x[i] = i + 1;
        }
        // 生成插值多项式
        int[][] polynomial = null;
        switch (type) {
            case TYPE_LAGRANGE:
                polynomial = LagrangeInterpolationUtil.polynomial(x, y);
                break;

            case TYPE_NEWTON:
                polynomial = NewtonInterpolationUtil.polynomial(x, y);
                break;
        }
        // 显示多项式
        latexString = LatexUtil.creatLatexString(polynomial);
        binding.tvResult.setText(latexString);
        // 显示验算
        binding.tvChecking.setText(LatexUtil.createCheckingString(polynomial));
    }

    // 显示提示
    private void showNotice(String noticeString) {
        Toast.makeText(this, noticeString, Toast.LENGTH_SHORT).show();
        binding.tvResult.setText(noticeString);
        binding.tvChecking.setText("");
    }

    // 保存按钮点击事件
    private void saveBtnClick() {
        if (TextUtils.isEmpty(latexString)) {
            Toast.makeText(this, "内容为空，无法保存", Toast.LENGTH_SHORT).show();
            return;
        }
        ImageUtil.saveImage(binding.tvResult);
    }
}